package org.readme.web;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.readme.mapper.LoginUserMapper;
import org.readme.pojo.LoginUser;
import org.readme.util.SqlSessionFactoryUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        System.out.println("loginServlet_doGet?");
        //接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //查询
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/
        //使用工具类
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        LoginUserMapper loginUserMapper = sqlSession.getMapper(LoginUserMapper.class);
        LoginUser loginUser = loginUserMapper.select(username, password);
        System.out.println(loginUser);
        sqlSession.close();

        //获取字符输出流
        PrintWriter writer = resp.getWriter();
        if (loginUser!=null){
            writer.write("登录成功");
        }else {
            writer.write("登陆失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("loginServlet_doPost?");
        this.doGet(req, resp);
    }
}
